package cn.edu.scau.cmi.linhongxin.orm.dao;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import cn.edu.scau.cmi.linhongxin.orm.domain.*;

public class StudentDAO extends BaseDAO{
	public void add(Student s) {
		Session session=getSession();
		Transaction tx=null;
		try {
			tx=session.beginTransaction();
			session.save(s);
			tx.commit();
		}catch (RuntimeException e) {
			// TODO: handle exception
			tx.rollback();
			throw e;
		}finally {
			session.close();
		}
	}
	public void update(Student s) {
		Session session=getSession();
		Transaction tx=null;
		try {
			tx=session.beginTransaction();
			String hql="Update Student s set s.name=:name,s.tutor=:tutor where s.id=:id";
			Query<Student> query=session.createQuery(hql);
			query.setParameter("name", s.getName());
			query.setParameter("tutor", s.getTutor());
			query.setParameter("id", s.getId());
			query.executeUpdate();
			tx.commit();
		}catch (RuntimeException e) {
			// TODO: handle exception
			tx.rollback();
			throw e;
		}finally {
			session.close();
		}
	}
	public void delete(int id) {
		Session session=getSession();
		Transaction tx=null;
		try {
			tx=session.beginTransaction();
			Object sObject=session.get(Student.class, id);
			session.delete(sObject);
			tx.commit();
		}catch (RuntimeException e) {
			// TODO: handle exception
			tx.rollback();
			throw e;
		}finally {
			session.close();
		}
	}
	public List<Student> findAll() {
		Session session=getSession();
		List<Student> list=null;
		try {
			String hql="from Student";
			@SuppressWarnings("unchecked")
			Query<Student> query=session.createQuery(hql);
			list=query.list();
		}catch (RuntimeException e) {
			// TODO: handle exception
			throw e;
		}finally {
			session.close();
		}
		return list;
	}
	public List<Student> findByProperty(String property,String value){
		Session session=getSession();
		List<Student> list=null;
		try {
			String hql="from Student where"+property+"='"+value+"'";
			@SuppressWarnings("unchecked")
			Query<Student> query=session.createQuery(hql);
			list=query.list();
		}catch (RuntimeException e) {
			// TODO: handle exception
			throw e;
		}finally {
			session.close();
		}
		return list;
	}
}
